<?php

class ValidadorHelper extends AppHelper {

    var $formName = ''; //Indica el formulario que sera validado
    var $forms = array(); //lleva un arreglo de todos los controlos html que seran validados
    var $idClient = array(); //controla un identificador del lado del cliente que permite saber donde se va a mostrar el error
    var $defaultMessages = array(); //Listado de los menajes de error generados
    var $specificMessages = array(); //Listado de los menajes de error generados
    var $rules = array(); //The rules for the validation
    var $j = '$';

    //constructor: recibe opcionalmente el formulario que va a validar
    function setFormulario($name = '') {
        $this->formName = $name;
        //$this->autoAdvance = true;
    }

    function setRules($itemForm, $rules = array()) {
        foreach ($rules as $key => $rule) {
            $tmp = explode('.', $itemForm);
            if (count($tmp) > 1) {
                $name = $tmp[0];
                for ($i = 1; $i < count($tmp); $i++) {
                    $name .= '[' . $tmp[$i] . ']';
                }
            } else
                $name = $itemForm;
            
            if (isset($rule['value']))
                $this->rules[$name][$key] = $rule['value'];
            if (isset($rule['field']))
                $this->rules[$name][$key] = $rule['field'];
            if (isset($rule['url']))
                $this->rules[$name][$key]['url'] = $rule['url'];
            if (isset($rule['async']))
                $this->rules[$name][$key]['async'] = $rule['async'];
            if (isset($rule['message']))
                $this->specificMessages[$name][$key] = $rule['message'];
        }
    }

    function setDefaultErrorMessages($messages = array()) {
        if (!empty($messages)) {
            echo '<script>jQuery.extend(jQuery.validator.messages, {';
            foreach ($messages as $key => $message)
                echo ' ' . $key . ': "' . $message . '", ';
            echo '});</script>';
        }
    }

    function printScript($etiqueta = false) {
        $result = '';
        if ($etiqueta)
            $result .= "\n<script>\n{$this->j}(function() {\n";
        $result .= "\t{$this->j}(\"#" . $this->formName . "\").validate({\n\tignore : false,\n\tonkeyup: false,
            invalidHandler: function(form, validator) {
                var tabSelect = function(element){
                    if(!{$this->j}(element).length)
                    return;
                    var tabs = {$this->j}(element).parents('.ui-tabs:eq(0)');
                    tabs.tabs({active: tabs.find('>div').index(element.parents('.ui-tabs-panel:eq(0)'))});
                    if(tabs.parents('.ui-tabs:eq(0)').length){
                        tabSelect(tabs);
                    }
                };
                var errors = validator.numberOfInvalids();
                if (errors) {
                    try {
                        var focused = {$this->j}(validator.findLastActive() || validator.errorList.length && validator.errorList[0].element || []);
                        tabSelect(focused);
                        focused.focus();
                    } catch(e) {
                    // ignore IE throwing errors when focusing hidden elements
                    }
                }
            },\n";
        if (!empty($this->rules)) {
            $result .= "\trules: {\n";
            $k = 0;
            foreach ($this->rules as $key => $rule) {
                if ($k == 0)
                    $result .= "\t\t\"" . $key . "\": {";
                else
                    $result .= ",\n\t\t\"" . $key . "\": {";
                $j = 0;
                foreach ($rule as $ruleName => $value) {
                    if ($j == 0)
                        $result .= $ruleName . ': ';
                    else
                        $result .= ", " . $ruleName . ': ';
                    if (is_array($value)) {
                        $result .= "{\n";
                        $i = 0;
                        foreach ($value as $subRuleName => $subValue) {
                            if ($i == 0)
                                $result .= "\t\t\t\t" . $subRuleName . ': ' . $subValue;
                            else {
                                $subValue = ($subValue) ? $subValue : 'false';
                                $result .= ",\n\t\t\t\t" . $subRuleName . ': ' . $subValue;
                            }
                            $i++;
                        }
                        $result .= "}";
                    } else
                        $result .= $value;
                    $j++;
                }
                $result .= "}";
                $k++;
            }
            $result .= "\n\t},\n";
            $result .= "\tmessages: {\n";
            $i = 0;
            foreach ($this->specificMessages as $key => $message) {
                if ($i == 0)
                    $result .= "\t\t\"" . $key . "\": {";
                else
                    $result .= ",\n\t\t\"" . $key . "\": {";
                $j = 0;
                foreach ($message as $messageType => $value) {
                    if ($j == 0)
                        $result .= $messageType . ': "' . $value . "\"";
                    else
                        $result .= ", " . $messageType . ': "' . $value . "\"";
                    $j++;
                }
                $result .= "}";
                $i++;
            }
            $result .= "\n\t}\n";
        }
        $result .= "\t});\n";
        /* if ($this->autoAdvance)
          $result .= "\n {$this->j}(\"#" . $this->formName . "\").autoAdvance(); "; */
        if ($etiqueta)
            $result .= "});\n</script>";
        echo $result;
    }

    function newSetRules($itemForm, $rules = array()) {
        foreach ($rules as $key => $rule) {
            $tmp = explode('.', $itemForm);
            if (count($tmp) > 1) {
                $name = $tmp[0];
                for ($i = 1; $i < count($tmp); $i++) {
                    $name .= '\\\[' . $tmp[$i] . '\\\]';
                }
            } else
                $name = $itemForm;
            if (isset($rule['value']))
                $this->rules[$name][$key] = $rule['value'];
            if (isset($rule['message']))
                $this->specificMessages[$name][$key] = $rule['message'];
        }
    }

    function newRules($etiqueta = true, $opcion = 'add') {
        $result = '';
        if ($etiqueta)
            $result .= "\n<script>\n";
        $result .= "{$this->j}(\"#" . $this->formName . "\").validate();\n";
        if (!empty($this->rules)) {
            foreach ($this->rules as $key => $rule) {
                $result .= "{$this->j}(\"#$key\").rules(\"$opcion\", {\n\t";
                $j = 0;
                foreach ($rule as $ruleName => $value) {
                    if ($j == 0)
                        $result .= $ruleName . ': ';
                    else
                        $result .= ",\n\t" . $ruleName . ': ';
                    if (is_array($value)) {
                        $i = 0;
                        foreach ($value as $subRuleName => $subValue) {
                            if ($i == 0)
                                $result .= "\t\t\t\t" . $subRuleName . ': ' . $subValue;
                            else
                                $result .= ",\n\t\t\t\t" . $subRuleName . ': ' . $subValue;
                            $i++;
                        }
                    } else
                        $result .= $value;
                    $j++;
                }
                if (isset($this->specificMessages[$key])) {
                    $result .= ",\n";
                    $result .= "\tmessages: {\n\t\t";
                    $j = 0;
                    foreach ($this->specificMessages[$key] as $index => $message) {
                        if ($j == 0)
                            $result .= $index . ': "' . $message . "\"";
                        else
                            $result .= ",\n\t\t" . $index . ': "' . $message . "\"";
                        $j++;
                    }
                    $result .= "\n\t}\n";
                }
                $result .= "});\n";
            }
        }
        if ($etiqueta)
            $result .= "\n</script>";
        echo $result;
    }

}
